import { AfterViewInit, Component, ElementRef, Input, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges } from '@angular/core';
import { ThreadsCollectBoardVo } from 'src/app/model/threads-collect-board-vo';
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';
import { ThreadsService } from 'src/app/services/threads.service';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-home-recent-result',
  templateUrl: './home-recent-result.component.html',
  styles: [``]
})
export class HomeRecentResultComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
  public recentCategory: string = 'threads';
  public recentThreads: ThreadsCollectBoardVo[] = [];
  @Input('uid')
  public uid!: number;
  private tabListenFunc!: any;
  
  constructor(private elementRef: ElementRef, private renderer2: Renderer2, private threadsService: ThreadsService) { }

  ngOnChanges(changes: SimpleChanges): void {
    if(changes['uid'].firstChange){
      console.log('[HomeRecentResult-Emd]is first');
      return;
    }
    console.log('[HomeRecentResult-Emd]is not first');
    if(changes['uid'].previousValue != changes['uid'].currentValue){
      this.uid = changes['uid'].currentValue;
      this.recentCategory = 'threads';
      this.fillThreadsResult();
    }
  }

  ngOnDestroy(): void {
    if (this.tabListenFunc) {
      this.tabListenFunc.unsubscribe();
    }
  }

  ngAfterViewInit(): void {
    this.tabListenFunc = fromEvent(this.elementRef.nativeElement.querySelectorAll('a.nav-link'), 'click').pipe(map((val: any) => val.target))
      .subscribe({
        next: res => {
          let anchorEle: HTMLElement = res as HTMLElement;
          this.toggleTab(anchorEle.getAttribute('data-tab'));
        },
        error: err => {
        },
        complete: () => {
          console.log('[HomeRecentResult-EMD]Event Completed');
        }
      });
  }

  ngOnInit(): void {
    this.fillThreadsResult();
  }

  private toggleTab(tabCategroy: string | null): void {
    if (!tabCategroy) {
      return;
    }
    if (this.recentCategory === tabCategroy) {
      return;
    }
    this.recentCategory = tabCategroy;
    if ('threads' === tabCategroy) {
      this.fillThreadsResult();
    }
    if ('reply' === tabCategroy) {
      this.fillReplyResult();
    }
  }

  private fillThreadsResult(): void {
    this.threadsService.getMemberPublish(this.uid ?? 0, environment.indexSize).subscribe(res=>this.recentThreads = res);
  }

  private fillReplyResult(): void {
    this.threadsService.getMemberReply(this.uid ?? 0, environment.indexSize).subscribe(res=>this.recentThreads = res);
  }
}
